package com.astroway.livetest.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astroway.livetest.R;
import com.astroway.livetest.model.ChatEntity;
import com.astroway.livetest.model.MessageModel;
import com.astroway.livetest.util.AnimatedGifDrawable;
import com.astroway.livetest.util.AnimatedImageSpan;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 崔健伟
 * @version V1.0
 * @Title: MessageAdapter.java
 * @Package com.astroway.livetest.adapter
 * @Description:
 * @date 2017/2/13 14:54
 */
public class MessageAdapter extends BaseAdapter {
    private static final String TAG = "MessageAdapter";
    private Context context;
    private List<ChatEntity> messageList;

    public MessageAdapter(Context context, List<ChatEntity> messageList) {
        this.context = context;
        this.messageList = messageList;
    }

    @Override
    public int getCount() {
        return messageList.size();
    }

    @Override
    public Object getItem(int position) {
        return messageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ChatEntity chatEntity = messageList.get(position);
        MessageModel messageModel = chatEntity.getMessageModel();
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_adapter_message, null);
            holder.textView = (TextView) convertView.findViewById(R.id.item_adapter_message_tv);
            holder.headImg = (ImageView) convertView.findViewById(R.id.item_adapter_message_head_img);
            holder.nickTv = (TextView) convertView.findViewById(R.id.item_adapter_message_nick_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Log.i(TAG, "getView: " + messageModel.getMessage());
        holder.nickTv.setText(messageModel.getNickName());
        DisplayImageOptions option = new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(false) // default
                .delayBeforeLoading(100)
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .cacheInMemory(true)
                .cacheOnDisk(true) // default 不缓存至手机SDCard
                .imageScaleType(ImageScaleType.EXACTLY)
                .showImageOnLoading(R.drawable.head_default)
                .showImageOnFail(R.drawable.head_default)
                .showImageForEmptyUri(R.drawable.head_default)
                .build();
        //        Log.i(TAG, "getView: " + messageModel.getHeadImg());
        ImageLoader.getInstance().displayImage(messageModel.getHeadImg(), holder.headImg, option);
        // 对内容做处理
        SpannableStringBuilder sb = handler(holder.textView, messageModel.getMessage());
        holder.textView.setText(sb);
        return convertView;
    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
        String regex = "(\\#\\[huikaoba_)\\d{3}(.png\\]\\#)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String tempText = matcher.group();
            try {
                String num = tempText.substring((context.getString(R.string.face_before)
                        + context.getString(R.string.message_face_before)).length(), tempText.length() -
                        (context.getString(R.string.png) + context.getString(R.string.face_ofter)).length());
                String gif = context.getString(R.string.gif_path)
                        + context.getString(R.string.message_face_before)
                        + num
                        + context.getString(R.string.gif);
                Log.i(TAG, "handler: " + num);
                Log.i(TAG, "handler: " + gif);
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = context.getAssets().open(gif);
                spannableStringBuilder.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = context.getString(R.string.png_path)
                        + context.getString(R.string.message_face_before)
                        + tempText.substring(context.getString(R.string.face_before).length(), tempText.length() -
                        context.getString(R.string.face_ofter).length());
                Log.i(TAG, "handler: " + png);
                try {
                    spannableStringBuilder.setSpan(new ImageSpan(context, BitmapFactory.decodeStream(context.getAssets().open(png))), matcher.start
                            (), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }
        return spannableStringBuilder;
    }

    class ViewHolder {
        TextView textView;
        ImageView headImg;
        TextView nickTv;
    }
}
